<template>
  <div style="height: 100%">
    <div class="header">
      <div class="selectRange">
        <Menu
            mode="horizontal"
            @on-select="(name) => $route.name !== name && $router.push(name)"
            :active-name="$route.name"
        >
          <MenuItem name="home"> 首页</MenuItem>
          <MenuItem name="health"> 健康指标</MenuItem>
          <MenuItem v-if="isRoleAdmin" name="patient-management"> 病患管理</MenuItem>
        </Menu>
      </div>
      <div class="header-title">医疗健康数据可视化平台</div>
      <div class="selectRange">
        <Menu
            mode="horizontal"
            @on-select="handleSelect"
            :active-name="activeName"
        >

          <Submenu name="4">
            <template slot="title">
              <Icon type="ios-settings-outline" size="24" color="#60C2D4"/>
            </template>

            <MenuItem v-if="isRoleAdmin" name="userInfo">个人中心</MenuItem>
            <MenuItem name="viewMessage">查看留言</MenuItem>
            <MenuItem name="sendMessage">留言反馈</MenuItem>
            <MenuItem v-if="isRoleAdmin" name="upload">上传文件</MenuItem>
            <MenuItem name="logout">退出登录</MenuItem>
          </Submenu>
        </Menu>
      </div>
    </div>
    <Modal
        v-model="modal"
        title="选择时间"
        :mask-closable="false"
        @on-ok="getMonthBetween(startTime, endTime)"
    >
      <DatePicker
          @on-change="pickStartDate"
          :options="optionStart"
          type="date"
          placeholder="选择开始日期"
          style="width: 200px"
      ></DatePicker>
      <span style="padding: 0 20px; color: #75deef">至</span>
      <DatePicker
          @on-change="pickEndDate"
          :options="optionEnd"
          type="date"
          placeholder="选择结束日期"
          style="width: 200px"
      ></DatePicker>
    </Modal>

    <!--查看留言-->
    <Modal
        v-model="dialogVisibleViewMessage"
        title="查看留言"
        :mask-closable="false"
        :footer-hide="true"
    >
      <viewMesssage></viewMesssage>
    </Modal>

    <!--留言反馈-->
    <Modal
        v-model="dialogVisibleSendMessage"
        title="留言反馈"
        :mask-closable="false"
        :footer-hide="true"
    >
      <sendMessage @closeSendMessageModel="closeSendMessageModel"></sendMessage>
    </Modal>


    <div class="page">
      <router-view v-if="flag" :selectRangeDate="selectRangeDate"></router-view>
    </div>
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
    >
      <span>确定退出登录吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="logOut">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 个人中心 -->
    <el-dialog
        title="用户中心"
        :visible.sync="dialogUserInfoVisible"
        width="30%"
        style=""
        :before-close="handleClose"
    >
      <div class="userInfo">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="用户名称">
            <el-input v-model="form.account" disabled></el-input>
          </el-form-item>
          <el-form-item
              label="邮箱"
              :rules="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              {
                type: 'email',
                message: '请输入正确的邮箱地址',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.sex">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input v-model="form.checkPass"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editUserInfo('form')">保存</el-button>
      </span>
    </el-dialog>
    <!-- 上传文件 -->
    <el-dialog
        title="文件上传"
        :visible.sync="dialogFileVisible"
        width="30%"
        style=""
        :before-close="handleFileClose"
    >
      <div class="userInfo">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="上传文件">
            <el-upload
                action=""
                class="upload-demo"
                :on-change="changeFile"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
                :auto-upload="false"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传csv文件，且不超过500M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addFile('form')">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {updataeUser} from "@/api/login.js";
import {uploadFile} from "@/api/upload.js";

const viewMesssage = () => import("./message/viewMessage");
const sendMessage = () => import("./message/sendMessage")

export default {
  name: "",
  components: {
    viewMesssage,
    sendMessage
  },

  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {
        account: "",
        email: "",
        sex: 1,
        password: "",
        checkPass: "",
      },
      fileList: [],
      dialogFileVisible: false,
      activeName: "month", // 默认显示近一月
      modal: false,
      flag: false,
      dialogVisible: false,
      dialogUserInfoVisible: false,
      selectRangeDate: [],
      startTime: "",
      endTime: "",
      optionStart: {
        disabledDate(date) {
          // 禁止选择今天之后的日期
          return date && date.valueOf() > Date.now() - 86400000;
        },
      },
      optionEnd: {},
      resizeFn: null,
      rules: {
        password: [
          {required: true, message: "请输入密码", trigger: "change"},
        ],
        checkPass: [{validator: validatePass2, trigger: "blur"}],
      },
      dialogVisibleViewMessage: false,
      dialogVisibleSendMessage: false
    };
  },
  mounted() {
    window.addEventListener("resize", this.resizeFn);
    this.handleSelect(this.activeName); // 默认显示近一个月
  },
  computed: {
    isRoleAdmin() {
      // 从 sessionStorage 获取 role 值
      const role = sessionStorage.getItem('role');
      // 如果 role 值为 'admin'，则返回 true，否则返回 false
      return role === 'admin';
    }
  },
  methods: {
    editUserInfo(formName) {
      //修改用户
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.form);
          updataeUser(this.form).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              this.handleClose();
              this.logOut();
            } else {
              this.$message.error(res.data);
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleClose() {
      this.$refs["form"].resetFields();
      this.dialogUserInfoVisible = false;
      this.form = {};
    },
    handleFileClose() {
      this.dialogFileVisible = false;
      this.fileList = [];
    },
    changeFile(file, fileList) {
      this.fileList = fileList;
    },
    addFile() {
      console.log(this.fileList[0].raw, 123321);
      uploadFile(this.fileList[0].raw).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.dialogFileVisible = false;

          this.$message({
            message: res.data,
            type: "success",
          });
        } else {
          this.$message.error(res.data);
        }
      });
    },
    pickStartDate(date) {
      // 选择开始时间的回调
      this.startTime = date;
      this.optionEnd = {
        disabledDate(d) {
          // 禁止选择开始时间之前的日期
          return d && d.valueOf() < new Date(date).valueOf() - 86400000;
        },
      };
    },
    pickEndDate(date) {
      // 选择结束时间的回调
      this.endTime = date;
    },
    getMonthBetween(start, end) {
      // 获取开始时间和结束时间之内的所有月份
      this.selectRangeDate = [];
      let s = start.split("-"); // 字符串装换数组
      let e = end.split("-");
      let date = new Date();
      let min = date.setFullYear(s[0], s[1] - 1); // 设置最小时间
      let max = date.setFullYear(e[0], e[1] - 1); // 设置最大时间
      let curr = min;
      while (curr <= max) {
        // 循环添加月份
        var month = curr.getMonth();
        var arr = [curr.getFullYear(), month + 1];
        this.selectRangeDate.push(arr);
        curr.setMonth(month + 1);
      }
    },
    getDays(day) {
      // 获取天数
      let arr = [];
      for (let i = -day; i < 0; i++) {
        // 循环添加天数
        let today = new Date(); // 获取今天
        let targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * i;
        today.setTime(targetday_milliseconds); //设置i天前的时间
        let tYear = today.getFullYear();
        let tMonth = today.getMonth();
        let tDate = today.getDate();
        let date = [tYear, tMonth + 1, tDate];
        arr.push(date);
      }
      return arr;
    },
    handleSelect(name) {
      switch (name) {
        case "day":
          break;
        case "week":
          this.selectRangeDate = this.getDays(7); // 获取近一周的天数
          this.flag = true;

          break;
        case "month":
          this.selectRangeDate = this.getDays(30); // 获取近一个月的天数
          this.flag = true;
          break;
        case "userInfo":
          if (sessionStorage.getItem("userInfo")) {
            const userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
            this.form.email = userInfo.email;
            this.form.account = userInfo.account;
            this.form.sex = userInfo.sex;
            console.log(userInfo);
          }
          this.dialogUserInfoVisible = true;
          break;
        case "upload":
          this.dialogFileVisible = true;
          break;
        case "logout":
          this.dialogVisible = true;
          break;
        case "filter":
          this.modal = true;
          break;
        case "viewMessage":
          this.dialogVisibleViewMessage = true;
          break;
        case "sendMessage":
          this.dialogVisibleSendMessage = true;
          break;
        default:
          break;
      }
    },
    logOut() {
      this.dialogVisible = false;
      this.$message({
        message: "操作成功",
        type: "success",
      });
      sessionStorage.clear();
      this.$router.push("/login");
    },
    closeSendMessageModel() {
      //  关闭发送消息弹框
      this.dialogVisibleSendMessage = false
    }
  },
};
</script>

<style lang="less">
.ivu-modal {
  .ivu-modal-content {
    background: #071332;

    .ivu-modal-header {
      border-bottom: 1px solid #1a3c58;

      .ivu-modal-header-inner {
        color: #75deef;
      }
    }

    .ivu-modal-body {
      text-align: center;

      .ivu-icon {
        color: #75deef;
      }

      .ivu-modal-confirm-body {
        padding-left: 0;
        color: #75deef;
      }

      .ivu-input {
        background-color: rgba(0, 0, 0, 0);
        border: 1px solid #1a3c58;
        color: #75deef;

        &::-webkit-input-placeholder {
          /* WebKit, Blink, Edge */
          color: #75deef;
        }

        &::-moz-placeholder {
          /* Mozilla Firefox 4 to 18 */
          color: #75deef;
        }

        &::-moz-placeholder {
          /* Mozilla Firefox 19+ */
          color: #75deef;
        }

        &::-ms-input-placeholder {
          /* Internet Explorer 10-11 */
          color: #75deef;
        }
      }

      .ivu-picker-panel-body {
        background: #071332;

        .ivu-date-picker-header {
          color: #75deef;
          border-bottom: 1px solid #1a3c58;
        }

        .ivu-date-picker-cells-cell {
          color: #75deef;

          &:hover em {
            background: #1a3c58;
          }
        }

        .ivu-date-picker-cells-cell-disabled {
          background: rgba(0, 0, 0, 0);
          color: #eee;
        }

        .ivu-date-picker-cells-focused em {
          box-shadow: 0 0 0 1px #1a3c58 inset;

          &::after {
            background: #1a3c58;
          }
        }
      }
    }

    .ivu-modal-footer {
      border-top: 1px solid #1a3c58;

      .ivu-btn-primary {
        color: #75deef;
        background: #1a3c58;
      }

      .ivu-btn-text {
        color: #ddd;

        &:hover {
          color: #75deef;
          background: #1a3c58;
        }
      }
    }
  }
}

.header {
  height: 80px;
  background: #03044a;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;

  &-title {
    color: #75deef;
    font-size: 35px;

    font-weight: bold;
    letter-spacing: 10px;
  }

  .selectRange {
    height: 100%;

    .ivu-menu-horizontal {
      background: rgba(255, 255, 255, 0);

      &::after {
        height: 0;
      }

      .ivu-menu-item-active {
        border-bottom: 2px solid #264e5e;
      }

      .ivu-menu-item,
      .ivu-menu-submenu {
        color: #75deef;

        &:hover {
          border-bottom: 2px solid #264e5e;
        }
      }

      .ivu-select-dropdown {
        background: #09102e;

        .ivu-menu-item {
          color: #75deef;

          &:hover {
            border-bottom: 2px solid #264e5e;
            background-color: rgba(255, 255, 255, 0);
          }
        }
      }

      .ivu-menu-submenu-title {
        i {
          margin-right: 0;
        }

        .ivu-icon-ios-arrow-down {
          display: none;
        }
      }
    }
  }
}

.page {
  height: calc(~"100% - 80px");
}
</style>
